import { HaoEncrypt } from "./HaoEncrypt"

const xlsx = require('node-xlsx')
const fs = require("fs")
const path = require("path")

let outputPath: string = path.resolve() + "/json/"
let erlOutputPath: string = path.resolve() + "/cfg/"
let inputPath: string = path.resolve() + "/excel"
console.log("outputPath====", outputPath);
console.log("inputPath====", inputPath);
let erlHStr: string = ""
let jsonList: Array<string> = []
let jsonNameList: Array<string> = []

function exportOneExcel(workSheetsFromFile) {
    for (let i = 0; i < workSheetsFromFile.length; i++) {
        let sheetObj = workSheetsFromFile[i];
        let sheetName = sheetObj["name"];
        // console.log("sheetName=", sheetName);
        let sheetData = sheetObj["data"];
        let formatList = [];
        let keyList = [];
        let clientDataList = [];
        let erlDataList = [];
        // let dataList = [];
        let outputTypeList = []
        let realFormatList: Array<string> = []
        for (let j = 0; j < sheetData.length; j++) {
            let oneRowData = sheetData[j];
            if (j == 1) {
                formatList = oneRowData
            }
            else if (j == 2) {
                keyList = oneRowData
            } else if (j == 3) {
                outputTypeList = oneRowData
            }
            else if (j > 2) {
                // let oneRowObj = {};
                let oneRowClient = {}
                let oneRowServer = {}
                for (let k = 0; k < oneRowData.length; k++) {
                    let cellData = oneRowData[k];
                    let key = keyList[k];

                    let format = formatList[k].toLowerCase();
                    // console.log("cellData=======", key, cellData);
                    let value = cellData;
                    realFormatList[k] = format
                    if (format == "array" || format == "object") {
                        realFormatList[k] = "any"
                        try {
                            value = JSON.parse(cellData);
                        } catch (error) {
                            // console.log("格式化错误=", key, format, cellData);
                        }
                    }
                    else if (format == "int") {
                        realFormatList[k] = "number"
                    }
                    // if (outputTypeList[k] == 0) {
                    oneRowClient[key] = value;
                    // oneRowServer[key] = value;
                    // }
                    // else if (outputTypeList[k] == 1) {
                    //     oneRowClient[key] = value;
                    // }
                    // else if (outputTypeList[k] == 2) {
                    //     oneRowServer[key] = value;
                    // }
                    // oneRowObj[key] = value;
                }
                // dataList.push(oneRowObj);
                clientDataList.push(oneRowClient);
                erlDataList.push(oneRowData);
            }
        }
        console.log("formatList=", formatList);
        console.log("outputTypeList=", outputTypeList);
        console.log("keyList=", keyList);
        console.log("clientDataList=", clientDataList);
        console.log("erlDataList=", erlDataList);
        // console.log("jsonStr=", jsonStr);
        // let filePath = outputPath + sheetName + ".json"
        console.log("sheetName=", sheetName);
        let jsonStr = JSON.stringify(clientDataList);
        exportClient(sheetName, jsonStr)
        exportConfigTs(sheetName, keyList, realFormatList)
        // exportErl(sheetName, erlDataList, outputTypeList, formatList, keyList);
    }
}

function exportClient(sheetName: string, jsonStr: string) {
    // let filePath = outputPath + sheetName + ".txt"
    // let encrystr: string = (jsonStr)
    // let encrystr: string = HaoEncrypt.encode(jsonStr)
    // fs.writeFile(filePath, encrystr, function (err) {
    //     if (err) {
    //         console.warn("writeFile==error", filePath);
    //     }
    // });
    jsonList.push("config/json/" + sheetName)
    jsonNameList.push("Config_"+sheetName)

    let jsonPath = outputPath + sheetName + ".json"
    fs.writeFile(jsonPath, jsonStr, function (err) {
        if (err) {
            console.warn("writeFile==error", jsonPath);
        }
    });

}

function exportErl(sheetName: string, erlDataList: Array<any>, outputTypeList: Array<any>, formatList: Array<any>, keyList: Array<any>) {
    let cfgKey: string = "cfg_" + sheetName;
    // -define(cfg_word,{id,zh,cn}).
    erlHStr += `-define(` + cfgKey + ",{"
    let erlPath: string = erlOutputPath + cfgKey + ".erl";

    console.log("erlPath=", erlPath, cfgKey, erlDataList);
    let outputStr: string = "-module(" + cfgKey + ").\n"
    outputStr +=
        `-export([
get/1,
all/0
])\n`
    for (let i = 0; i < erlDataList.length; i++) {
        let oneRowData = erlDataList[i]
        console.log("oneRowData=", oneRowData);
        outputStr += `get(` + (i + 1) + `) ->#` + cfgKey + "{";
        for (let j = 0; j < oneRowData.length; j++) {
            if (outputTypeList[j] == 0 || outputTypeList[j] == 2) {
                if (i == 0) {
                    erlHStr += keyList[j] + ","
                }
                if (formatList[j] == "string") {
                    outputStr += keyList[j] + `="` + oneRowData[j] + `",`
                } else {
                    outputStr += keyList[j] + `=` + oneRowData[j] + ","
                }
            }

        }
        if (i == 0) {
            erlHStr = erlHStr.substring(0, erlHStr.length - 1);
            erlHStr += "}).\n"
        }
        outputStr = outputStr.substring(0, outputStr.length - 1);
        outputStr += "};\n"
    }
    outputStr += "get(_) -> null.";

    outputStr += "\nall() ->\n"
    outputStr += "["
    for (let i = 0; i < erlDataList.length; i++) {
        let oneRowData = erlDataList[i]
        if (i == 0) {
            outputStr += `#` + cfgKey + "{";
        } else {
            outputStr += `,#` + cfgKey + "{";
        }
        for (let j = 0; j < oneRowData.length; j++) {
            if (outputTypeList[j] == 0 || outputTypeList[j] == 2) {
                if (formatList[j] == "string") {
                    outputStr += keyList[j] + `="` + oneRowData[j] + `",`
                } else {
                    outputStr += keyList[j] + `=` + oneRowData[j] + ","
                }
            }

        }
        outputStr = outputStr.substring(0, outputStr.length - 1);
        outputStr += "}"
    }
    outputStr += "]."
    fs.writeFile(erlPath, outputStr, function (err) {
        if (err) {
            console.warn("writeFile==error", erlPath);
        }
    });
    exportHrl()
}

function exportHrl() {
    let hrlPath: string = erlOutputPath + "cfg.hrl"
    console.log("erlHStr=", erlHStr)
    fs.writeFile(hrlPath, erlHStr, function (err) {
        if (err) {
            console.warn("writeFile==error", hrlPath);
        }
    });
}

function searchDir(inputPath) {
    //根据文件路径读取文件，返回文件列表  
    let files = fs.readdirSync(inputPath)
    //遍历读取到的文件列表  
    files.forEach((filename) => {
        //获取当前文件的绝对路径  
        let filedir = path.join(inputPath, filename);
        // console.log("filedir==", filedir);
        //根据文件路径获取文件信息，返回一个fs.Stats对象  
        let stats = fs.statSync(filedir)
        let isFile = stats.isFile(); //是文件  
        let isDir = stats.isDirectory(); //是文件夹  
        if (isFile) {
            // console.log("filedir=============2", filedir, isFile);
            let workSheetsFromFile = xlsx.parse(filedir);
            console.log("workSheetsFromFile=", workSheetsFromFile);
            exportOneExcel(workSheetsFromFile)
        }
        if (isDir) {
            searchDir(filedir); //递归，如果是文件夹，就继续遍历该文件夹下面的文件  
        }
    });
}

function exportConfigTs(sheetName: string, keyList, realFormatList) {
    let outputStr = `
import { ConfigJsonBase } from "./ConfigJsonBase";

export class `
    outputStr += "Config_" + sheetName + " extends ConfigJsonBase {"
    outputStr += `\n  public static NAME:string = ` + `"` + sheetName + `"`
    for (let i = 0; i < keyList.length; i++) {
        outputStr += `\n public ` + keyList[i] + ":" + realFormatList[i] + ";"
    }
    outputStr += `\n public static configList:Array<` + "Config_" + sheetName + `> = []`
    outputStr += `\n public static json2Object(json: any) {
        for (const key in json) {
            `
    outputStr += `let config:` + "Config_" + sheetName + " = new " + "Config_" + sheetName + "()"
    for (let i = 0; i < keyList.length; i++) {
        outputStr += `\nconfig.` + keyList[i] + ` = json[key]["` + keyList[i] + `"];`
    }
    outputStr += "\n this.configList.push(config)\n}\n}"
    outputStr += `
    
}
    `

    let configJsonPath = path.resolve() + "/ts/Config_" + sheetName + ".ts"
    fs.writeFile(configJsonPath, outputStr, function (err) {
        if (err) {
            console.warn("writeFile==error", configJsonPath);
        }
    });
}

function exportConfigJson() {
    let str:string = ""
    for (let i = 0; i < jsonNameList.length; i++) {
        str += `import { `+jsonNameList[i]+`} from "./`+jsonNameList[i]+`"\n`
    }

    str += `
export class ConfigJson {

    public static jsonList: Array<string> = [
    `
    for (let i = 0; i < jsonList.length; i++) {
        if (i == jsonList.length - 1) {
            str += `"` + jsonList[i] + `"`
        } else {
            str += `"` + jsonList[i] + `",\n`
        }
    }
    console.log("jsonList===", jsonList)
    str += `
    ]`
    str += `\n public static initJson(resource:cc.JsonAsset){`

    for (let i = 0; i < jsonNameList.length; i++) {
        if(i == 0){
            str += `\n if(resource.name == `+jsonNameList[i]+".NAME){\n"
        }else{
            str += `\n else if(resource.name == `+jsonNameList[i]+".NAME){\n"
        }
        str += jsonNameList[i]+".json2Object(resource.json)\n}"
    }
    str += "}"

    str += `
}
    `

    let configJsonPath = path.resolve() + "/ts/ConfigJson.ts"
    fs.writeFile(configJsonPath, str, function (err) {
        if (err) {
            console.warn("writeFile==error", configJsonPath);
        }
    });


}

function main() {
    searchDir(inputPath)
    exportConfigJson()
    // exportHrl()
}

main();
